package gui.refresher;

import gui.*;
import gui.refresher.RefresherTask;

/**
 *
 * @author Marcin Kamionowski
 */
public class Refresher extends Thread {

    private final int milisec;
    private volatile boolean stop;
    private final RefresherTask task;
    private final int div;
    private boolean done = false;

    public Refresher(RefresherTask task, Object args[], int milisec) throws WrongValue {
        if (milisec < 100) {
            throw new WrongValue("Time must be longer than 100ms");
        }
        this.milisec = milisec;
        this.task = task;
        stop = false;
        task.initTask(args);
        div = 4;
    }

    public void run() {
        int period = milisec / div;
        int counter = 0;
        while (true) {
            if (!stop) {
                counter++;
                if (counter >= div && done == false) {
                    task.doTask();
                    done = true;
                    counter = 0;
                }else if(counter >= div * 20){
                    System.err.println("Refresher: run(): waiting too much - no response " +
                            "on last request");
                }
            }
            try {
                Thread.sleep(period);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopTask() {
        stop = true;
    }

    public void wakeTask() {
        done = false;
    }
}
